﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Box2D.XNA;
using Microsoft.Xna.Framework.Media;
using Microsoft.Devices.Sensors;

namespace Elementum
{
    class Stage5_1 : Stage
    {
        const int FOCUS_TIME = 100;
        public Stage5_1(Game game) : base(game) { }
        int focusTime = FOCUS_TIME;
        float GROUND_ALPHA = 0f;
        MechanismGound m;
        //MicSound mic;
        List<SnowBall> snowBallList = new List<SnowBall>();
        //Accelerometer _acceleMeter;
        Vector3 _accelReading = new Vector3();
        GroundObject underBund;
        GroundObject _grount;
        Boolean startMoving = false;

        public override void InitializeScenes()
        {
            base.InitializeScenes();

            Animation title = new Animation("images/title/stageTitle", new Rectangle(2, 190, 154, 46), new Point(154, 46));
            title.Scale = 1.2f;

            Transition tra = new DefauldTransition(1, 0, 0, 60);
            tra.Register(this);
            tra = new TitleTransition(title, new Vector2(200, 274), 0, 1, 80, 220);
            tra.Register(this);

            GroundObject grount;
           

            for (int i = 0; i < 4; i++)
            {
                Animation a = new Animation("images/stages/stage1/m" + i);
                a.LayerDepth = 0.9f;
                _backGround.Add(a);
            }

            _backGroundPos = new Vector2(-200, -200);
            _scenceBound = new Rectangle(75, -50,
                  1700, 570);
            camera.Bound = _scenceBound;
            camera.MoveSpeed = 5f;

            for (int i = 0; i < 3; i++)
            {
                Animation wallBack = new Animation("images/stages/stage5.1/stage5.1_" + i);
                //wallBack.LayerDepth = 0.9f;
                _wallBackGround.Add(wallBack);
            }
            _wallBackGroungPos = new Vector2(-274, -258);
            //if(mic==null)
            //mic = new MicSound(60);
            grount =
            StateFactory.CreateGround(this, -104, 334, 178, 471, 0f); grount.Alpha = GROUND_ALPHA; grount =
            StateFactory.CreateGround(this, 294, 544, 617, 50, 0f); grount.Alpha = GROUND_ALPHA; 
            StateFactory.CreatePortal("Stage5_1_Protal_1", this, 230, 469, "stage1_1", "Stage1_1_Portal_2");
            underBund = 
            StateFactory.CreatekillBund(this, 915, 588, 640, 64, 0);grount =
            StateFactory.CreateGround(this, 1443, 363, 406, 50, 0.15f); grount.Alpha = GROUND_ALPHA; grount =
            StateFactory.CreateGround(this, 1269, 512, 50, 216, 0f); grount.Alpha = GROUND_ALPHA; grount =
            StateFactory.CreateGround(this, 1759, 98, 501, 19, 0.4f); grount.Alpha = GROUND_ALPHA; grount =
            StateFactory.CreateGround(this, 1812, 333, 343, 50, 0f); grount.Alpha = GROUND_ALPHA; 
            StateFactory.CreatePortal("Stage5_1_Protal_2", this, 1770, 258, "stage5", "stageSnowProtal1");grount =
            StateFactory.CreateGround(this, 2101, 128, 236, 460, 0f); grount.Alpha = GROUND_ALPHA; _grount =
            StateFactory.CreateGround(this, 1567, 144, 43, 12, -1.1f); _grount.CurrentAnimation = new Animation("images/stages/stage5.1/branch",new Rectangle(2,2,43,12),new Point(43,12));
            _grount.Alpha = 1;
            _grount.GetBody().SetType(BodyType.Dynamic);
            Filter filter = new Filter();
            filter.categoryBits = 0x00;
            filter.maskBits = 0x00;
            _grount._fixture.SetFilterData(ref filter);
            m =
            StateFactory.CreateMechanismGound(this, 1553, 161, 10, 31, -0.55f, 0, 1000, 0, 1);
            m.CurrentAnimation = new Animation("images/stages/stage5.1/branch", new Rectangle(47, 2, 10, 31), new Point(10, 31));
            SnowBall s = new SnowBall(this._world, this, 0.6f);
            s.LifeTime = (int)GameClass.RandomBetween(3400, 3500);
            s.GetBody()._userData = "snowball";
            s.IniPosition = new Vector2(1610, (float)(99));//生成位置
            snowBallList.Add(s);
            Actors.Add(s);

            //_acceleMeter = new Accelerometer();
            GameClass._acceleMeter.ReadingChanged += GSensorChanged;
            try
            {
                GameClass._acceleMeter.Start();
            }
            catch (AccelerometerFailedException e) { }
            catch (UnauthorizedAccessException e) { }


            Font = ResourceManager.LoadSpriteFont("SpriteFont1");

            _song = MusicManager.LoadSong("Music/stage5");

            if (GameClass._musicString == "Music/stage5")
            { }
            else
            {
                GameClass._musicString = "Music/stage5";
                MediaPlayer.Play(_song);
            }
           // MediaPlayer.Volume = 1f;
            MediaPlayer.IsRepeating = true;

            _startProtal = new ProtalCommand("stage5_1", "Stage5_1_Protal_2");
        }

        void GSensorChanged(object sender, AccelerometerReadingEventArgs e)
        {
            _accelReading.X = (float)e.X;
            _accelReading.Y = -(float)e.Y;
            _accelReading.Z = (float)e.Z;
        }

        int temp1 = 0;

        public override void Instance_ShakeGesture(object sender, ShakeGestures.ShakeGestureEventArgs e)
        {
            base.Instance_ShakeGesture(sender, e);
            temp1++;
            if (temp1 == 1)
            {
                UpdateAction += MakeSnowBalls;
            }
        }

        private void MakeSnowBalls()
        {
            m.ChangeState();
            FocusTarget f = new FocusTarget(new Vector2(1500, 80));
            camera.Focus = f;

            startMoving = true;

            for (int i = 0; i < 4; i++)
            {
                scale = 0.6f;
                SnowBall s = new SnowBall(this._world, this, scale);
                s.LifeTime = (int)GameClass.RandomBetween(3400, 3500);
                s.GetBody()._userData = "snowball";
                s.IniPosition = new Vector2(1785, (float)(-200));//生成位置
                snowBallList.Add(s);
                Actors.Add(s);
            }
        }



        public override void Restart()
        {
            base.Restart();
            foreach (SnowBall snowBall in snowBallList)
                snowBall.Restart();
            foreach (VisibleObject b in actors)
            {
                b.Restart();
            }
            StageManager.ProtalCommand = _startProtal;
        }

        Random rand = new Random();


        public override Stage Clone()
        {
            Stage5_1 stage = new Stage5_1(Game);
            stage.InitializeScenes();
            return stage;
        }

        float scale = 0.4f;//大小=108*scale
        int number = 3;//15顆
        string snowData = "snowball";

        public override void Update(int delta)
        {
            base.Update(delta);
            if (camera.Focus != player && focusTime > 0)
            {
                focusTime--;
                _grount.Alpha -= 0.01f;
            }
            if (focusTime == 0)
            {
                camera.Focus = player;
                _grount.Position = new Vector2(2000, 2000);
            }

            //GameClass._mic.Update();
            float acc = 0f;

            if (startMoving)
            {
                acc = _accelReading.Y / 20;// (float)Math.Sqrt(_accelReading.Y);
                if (Math.Abs(acc) < (0.3 / 20)) acc = 0;
                for (int i = 0; i < snowBallList.Count; i++)
                {
                    snowBallList[i].GetBody().SetLinearVelocity(new Vector2(snowBallList[i].GetBody().GetLinearVelocity().X + acc,
                        snowBallList[i].GetBody().GetLinearVelocity().Y));
                }
            }

            //if (_accelReading.Y > 0.5)
            //{
            //    acc = _accelReading.Y / 2;
            //    for (int i = 0; i < snowBallList.Count; i++)
            //    {
            //    //    if(acc>0)//
            //        snowBallList[i].GetBody().SetLinearVelocity(new Vector2(snowBallList[i].GetBody().GetLinearVelocity().X+acc,
            //            snowBallList[i].GetBody().GetLinearVelocity().Y));
            //    }
            //}
            //else if (_accelReading.Y > -0.5)
            //{
            //    acc = _accelReading.Y / 2;
            //}
            //else 
            //{
            //    acc = _accelReading.Y / 2;
            //    for (int i = 0; i < snowBallList.Count; i++)
            //    {
            //        snowBallList[i].GetBody().SetLinearVelocity(new Vector2(snowBallList[i].GetBody().GetLinearVelocity().X + acc,
            //            snowBallList[i].GetBody().GetLinearVelocity().Y));
            //    }
            //}

            //for (int i = 0; i < snowBallList.Count; i++)
            //{
            //    if (snowBallList[i].IsLife == false)
            //    {
            //        Actors.Remove(snowBallList[i]);
            //        _world.DestroyBody(snowBallList[i].GetBody());
            //        snowBallList.Remove(snowBallList[i]);
            //    }
            //}
        }

        public override void OnDraw(SpriteBatch spriteBatch, int delta)
        {
            GraphicsDevice.Clear(Color.White);
            base.OnDraw(spriteBatch, delta);
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, camera.Transform);

            foreach (VisibleObject b in actors)
                b.OnDraw(spriteBatch, camera.Transform);

            spriteBatch.End();

            

        }

        public override void Dispose()
        {
            //mic._microphone.Stop();
            base.Dispose();
            //mic.Dispose();
        }

    }
}
